﻿#If NETFX_CORE Or WINDOWS_PHONE Then

Imports Microsoft.Xna.Framework
Imports Microsoft.Xna.Framework.Input.Touch
Imports Runa.Foundation.CompoentModel
Imports Runa.Foundation.Messaging

Namespace Global.Runa.UI.Input

    Public Class TouchPadInputHandler
        Inherits InputHandler

        Private m_state As New TouchCollection
        Private m_sample As New GestureSample
        Private m_capabilities As New TouchPanelCapabilities

        <MessageMapping(New String() {"Touch", "Gesture"}, New MessageType() {MessageType.WM_TOUCH, MessageType.WM_GESTURE})> _
        Public Property EnabledGestures() As GestureType
        Public Property EnableGesture() As Boolean

        Public ReadOnly Property IsConnected() As Boolean
            Get
                Return Me.m_capabilities.IsConnected
            End Get
        End Property

        Public Event Touch(ByVal sender As Object, ByVal e As TocuhPadInputEventArgs)
        Public Event Gesture(ByVal sender As Object, ByVal e As TocuhPadInputEventArgs)

        Public Sub New(ByVal g As Game)
            MyBase.New(g)
            Me.EnableGesture = False
            Me.EnabledGestures = GestureType.Tap Or GestureType.VerticalDrag Or GestureType.HorizontalDrag Or GestureType.Hold
            Me.m_capabilities = TouchPanel.GetCapabilities()
            If Me.m_capabilities.IsConnected = False Then
                Me.Enabled = False
            End If
        End Sub

        Public Overrides Sub Update(gameTime As GameTime)
            If Me.Game.IsActive And Me.Enabled Then
                Me.m_capabilities = TouchPanel.GetCapabilities()
                If Me.m_capabilities.IsConnected Then
                    Me.m_state = TouchPanel.GetState()
                    Me.m_sample = TouchPanel.ReadGesture()
                    Dim tie = GenerateTouchPadInputEventArgs(Of Object)(MessageType.WM_TOUCH, "TouchState", Nothing, Nothing)
                    RaiseEvent Touch(Me, tie)
                    MyBase.OnDataArrived(Me, tie)
                    If Me.EnableGesture Then
                        tie = GenerateTouchPadInputEventArgs(Of Object)(MessageType.WM_GESTURE, "TouchState", Nothing, Nothing)
                        RaiseEvent Gesture(Me, tie)
                        MyBase.OnDataArrived(Me, tie)
                    End If
                End If
            End If
        End Sub

        Private Function GenerateTouchPadInputEventArgs(Of T)(ByVal msg As MessageType, ByVal pName As String, ByVal oldValue As T, ByVal newValue As T) As TocuhPadInputEventArgs
            Return New TocuhPadInputEventArgs(msg, Me.m_state, Me.m_sample, New ChangedPropertyInf(Of Object)(pName, newValue, oldValue))
        End Function

    End Class

End Namespace

#End If